package com.situ.blog.controller;

import com.situ.blog.pojo.Blog;
import com.situ.blog.service.IBlogService;
import com.situ.blog.service.impl.BlogServiceImpl;
import com.situ.blog.util.JSONResult;
import com.situ.blog.util.JSONUtil;
import com.situ.blog.util.LayUITableJSONResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private IBlogService blogService = new BlogServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
        }
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("BlogServlet.add");
        String title = req.getParameter("title");
        String typeId = req.getParameter("typeId");
        String image = req.getParameter("image");
        String content = req.getParameter("content");
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setTypeId(Integer.parseInt(typeId));
        blog.setImage(image);
        blog.setContent(content);
        JSONResult jsonResult = blogService.add(blog);
        JSONUtil.obj2Json(jsonResult, resp);
    }

    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("BlogServlet.selectByPage");
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        LayUITableJSONResult layUITableJSONResult = blogService.selectByPage(Integer.parseInt(page), Integer.parseInt(limit));
        JSONUtil.obj2Json(layUITableJSONResult, resp);
    }
}
